package com.study.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.study.entity.*;
import com.study.mapper.EmpExprMapper;
import com.study.mapper.EmpMapper;
import com.study.service.EmpLogService;
import com.study.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogService empLogService;

    /*    @Override//分页查询
        public PageBean list(Integer page, Integer pageSize) {
        *//*    Long total =  empMapper.count();
        Integer startPage = (page-1)*pageSize;
        log.info("开始的数：{},展示总数：{}",startPage,pageSize);
        List<Emp> emps = empMapper.list(startPage,pageSize);*//*

//        使用分页依赖优化写法
        PageHelper.startPage(page,pageSize);

        //分也只会对PageHelper.startPage(page,pageSize)下面第一条SELECT进行处理
        Page p = (Page)empMapper.list();
        Long total = p.getTotal();
        List<Emp> emps = p.getResult();
        return new PageBean(total,emps);
    }*/
    @Override//条件分页查询
    public PageBean list(EmpQueryParam param) {

        PageHelper.startPage(param.getPage(), param.getPageSize());
        Page p = (Page) empMapper.list(param);
        Long total = p.getTotal();
        List<Emp> emps = p.getResult();
        return new PageBean(total, emps);
    }

    //rollbackfor属性用于控制出现何种异常类型才回滚事务，默认是运行时异常
    //propagation属性是事物的传播行为控制：一个事务方法调用另一个事务方法时，事务应该如何控制（加入/新建...）
    //REQUIRED:（默认）需要事务，有则加入，无则创建新事务（大部分场景）
    //REQUIRES_NEW:需要新事务，无论有无，总是创建新事务（希望两个方法在独立的事务中运行，互不影响）
    @Transactional(rollbackFor = RuntimeException.class)//开启事务
    @Override
    public void add(Emp emp) {
        try {
            emp.setPassword("123456");
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            empMapper.insertEmp(emp);
            Integer id = emp.getId();
            log.info("通过keysproperty拿到主键id:{}", id);
//            int i =1/0;
            List<EmpExpr> exprList = emp.getExprList();
            if (exprList.size() != 0 && exprList != null) {
                for (EmpExpr empExpr : exprList) {
                    empExpr.setEmpId(id);
                }
                empExprMapper.add(exprList);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //需求：在新增员工信息时，无论成功还是失败，都要记录操作日志
            empLogService.add(new EmpLog(null, LocalDateTime.now(), "添加员工：" + emp));
        }
    }

    @Transactional
    @Override
    public void remove(Integer[] ids) {
        empMapper.delete(ids);
        empExprMapper.delete(ids);
    }

    @Override
    public Emp selecyById(Integer id) {
        Emp emp = empMapper.selectById(id);

        return emp;
    }

    @Override
    @Transactional
    public void update(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);
        List<EmpExpr> exprList = emp.getExprList();
        if (exprList.size() != 0 && exprList != null) {
            empExprMapper.delete(new Integer[]{emp.getId()});
            empExprMapper.add(exprList);
        }
    }

    @Override
    public List<Emp> listAll() {
        List<Emp> list = empMapper.selectAll();
        return list;
    }

    @Override
    public List<Map<String, Object>> countGender() {
        Map<String, Object> map1 = new LinkedHashMap<>();
        Integer male = empMapper.countMale();
        map1.put("name", "男性员工");
        map1.put("value", male);
        Integer femele = empMapper.countFemale();
        Map<String, Object> map2 = new LinkedHashMap<>();
        map2.put("name", "女性员工");
        map2.put("value", femele);
        List<Map<String, Object>> list = new ArrayList<>();
        list.add(map1);
        list.add(map2);
        return list;
    }

    @Override
    public Map<String, Object[]> countJob() {
        Map map = new HashMap();
        List<InfoCount> counts = empMapper.countJob();
        int length = counts.size();
        String[] jobs = new String[length];
        Integer[] couns = new Integer[length];
        int i = 0;
        for (InfoCount count : counts) {
            jobs[i] = (String) count.getInfo();
            couns[i] = count.getCount();
            i++;
        }
        map.put("jobList", jobs);
        map.put("dataList", couns);

        return map;
    }
}
